import json
import io
from minio import Minio

class Store (object):

    def __init__(self, config):
        self._config = config
        self._baseKey = "market/{}/{}.list".format(self._config.root, self._config.root)

        self._client = Minio(self._config.endpoint,
                  access_key=self._config.id,
                  secret_key=self._config.secret,
                  secure=False)

    def load(self, key):
        try:
            response = self._client.get_object(self._config.bucket, key)
            if response.status == 200 and response.data:
                body_bytes = response.data
                body_str = body_bytes.decode('utf-8')
                return json.loads(body_str)
            else:
                raise ValueError("load {} empty with reason {}".format(key, response.reason))                
        
        except Exception as ex:
            raise ConnectionError("can not get object" + key + ex)
        
        finally:
            response.close()
            response.release_conn()
        
    def load_list(self, prefix):

        try:
            objects  = self._client.list_objects(self._config.bucket, prefix=prefix)
            return objects
        
        except Exception as ex:
            raise ConnectionError("can not get object" + prefix + ex)
        
    def save(self, code, year, data):

        try:
            key = "{}/{}/{}-{}.fdu".format(self._config.root, code, code, year)
            buff = json.dumps(data)
            if buff:
                buff = buff.encode('utf-8')
                return self._client.put_object(self._config.bucket, key, io.BytesIO(buff), length=-1, part_size=10*1024*1024 )
        
        except Exception as ex:
            raise ConnectionError("can not save object {} {}".format(code, year))